package com.blogspot.marekotulakowski.remotemanage;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class RemoteManage extends Activity implements OnClickListener {
    //Variables
	private Button buttonStart;
	private Button buttonStop;
	private TextView textViewIp;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //initialize controls variable events
        buttonStart = (Button)this.findViewById(R.id.buttonStart);
        buttonStart.setOnClickListener(this);
        buttonStop = (Button)this.findViewById(R.id.buttonStop);
        buttonStop.setOnClickListener(this);
        textViewIp = (TextView)this.findViewById(R.id.textViewIp);
        
        //start state
        this.buttonStart.setEnabled(true);
        this.buttonStop.setEnabled(false);
    }
    
    public void onClick(View arg0) {
    	if (arg0 == this.buttonStart) {
    		this.buttonStart.setEnabled(false);
    		this.buttonStop.setEnabled(true);  		
    		
    		textViewIp.setText(getLocalIpAddress());
    		
    	} else if (arg0 == this.buttonStop) {
    		this.buttonStart.setEnabled(true);
    		this.buttonStop.setEnabled(false);
    		
    		textViewIp.setText("NULL");
    	} 
    }
    
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        	//ignore
        }
        return "Can't read local IP";
    }
}